package com.mvc.web.common.push;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.payload.APNPayload.SimpleAlertMsg;
import com.gexin.rp.sdk.base.uitls.AppConditions;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.mvc.web.common.utils.PropertiesUtil;
import com.mvc.web.common.utils.ToolsUtils;

/**
 * @Description: 消息推送
 * @author 白海安 （baihaian@126.com） 2016年7月9日 下午3:50:51
 * @version V1.0
 */
public class PushMsgUtil {

	private static final String host = "http://sdk.open.api.igexin.com/apiex.htm";
	private static String appId = PropertiesUtil.getAppId();
	private static  String appKey = PropertiesUtil.getAppKey();
	private static String masterSecret = PropertiesUtil.getMasterSecret();
	
	
	/**   
	* @Description: 消息推送，个推
	* @author 白海安 （baihaian@126.com） 2016年8月22日 下午7:23:44
	* @version V1.0   
	*/
	public static Map<String, Object> PushTransmissiontoSingle(String cid,String content,String desc) {
		if(ToolsUtils.isNotEmpty(cid)){
			IGtPush push = new IGtPush(host, appKey, masterSecret);
			TransmissionTemplate template = transmissionTemplate(content,desc);
			SingleMessage message = new SingleMessage();
			message.setOffline(true);
			// 离线有效时间，单位为毫秒，可选
			message.setOfflineExpireTime(24 * 3600 * 1000);
			message.setData(template);
			// 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
			message.setPushNetWorkType(0);
			Target target = new Target();
			target.setAppId(appId);
			target.setClientId(cid);
			// target.setAlias(Alias);
			IPushResult ret = null;
			try {
				ret = push.pushMessageToSingle(message, target);
			} catch (RequestException e) {
				e.printStackTrace();
				ret = push.pushMessageToSingle(message, target, e.getRequestId());
			}
			if (ret != null) {
				System.out.println(ret.getResponse().toString());
				return ret.getResponse();
			} else {
				System.out.println("服务器响应异常");
			}
		}
		return null;
	}
	
	
	public static TransmissionTemplate transmissionTemplate(String content,String desc) {
	    TransmissionTemplate template = new TransmissionTemplate();
	    template.setAppId(appId);
	    template.setAppkey(appKey);
	    // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
	    template.setTransmissionType(2);
	    template.setTransmissionContent(content);
	    APNPayload pay = new APNPayload();
	    SimpleAlertMsg alert = new SimpleAlertMsg(desc);
	    pay.setAlertMsg(alert);
	    pay.setAutoBadge("+1");
	    template.setAPNInfo(pay);
	    // 设置定时展示时间
	    return template;
	}

	
	public static void PushTransmissiontoList(List<String> cids,String content) {
		if(cids != null && cids.size()>0){
			// 配置返回每个用户返回用户状态，可选
	        System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
	        // 配置返回每个别名及其对应cid的用户状态，可选
	        // System.setProperty("gexin_pushList_needAliasDetails", "true");
	        IGtPush push = new IGtPush(host, appKey, masterSecret);
	        // 通知透传模板
	        NotificationTemplate template = notificationTemplateDemo();
	        ListMessage message = new ListMessage();
	        message.setData(template);
	        // 设置消息离线，并设置离线时间
	        message.setOffline(true);
	        // 离线有效时间，单位为毫秒，可选
	        message.setOfflineExpireTime(24 * 1000 * 3600);
	        // 配置推送目标
	        List<Target> targets = new ArrayList<Target>();
	        for(String str :cids){
	        	Target target = new Target();
	        	target.setAppId(appId);
	 	        target.setClientId(str);
	 	        targets.add(target);
	        }
	        // taskId用于在推送时去查找对应的message
	        String taskId = push.getContentId(message);
	        IPushResult ret = push.pushMessageToList(taskId, targets);
	        System.out.println(ret.getResponse().toString());
		}
	}
	
	
	public static NotificationTemplate notificationTemplateDemo() {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 设置通知栏标题与内容
        template.setTitle("请输入通知栏标题");
        template.setText("请输入通知栏内容");
        // 配置通知栏图标
        template.setLogo("icon.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        template.setTransmissionContent("请输入您要透传的内容");
        return template;
    }
	
	
	public static void PushToApp(String content) throws Exception{
		String appId = "iT1jNA5YF47k0tZcitglm9";
	    String appKey = "NN6HinJail73uhWQFcGM41";
	    String masterSecret = "hWUINF1y6l9IMqyzIpq9iA";
		IGtPush push = new IGtPush(host, appKey, masterSecret);
		TransmissionTemplate template = transmissionTemplate(content,"");
        AppMessage message = new AppMessage();
        message.setData(template);
        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        //推送给App的目标用户需要满足的条件
        AppConditions cdt = new AppConditions(); 
        List<String> appIdList = new ArrayList<String>();
        appIdList.add(appId);
        message.setAppIdList(appIdList);
        message.setConditions(cdt); 
        IPushResult ret = push.pushMessageToApp(message,"APP版本更新");
        System.out.println(ret.getResponse().toString());
	}
	
	
	public static void main(String[] args) {
		try {
			String data = "{'detail': '* 【销售】查看金融产品列表\r\n* 【销售】基于金融产品建设销售进件合同流程\r\n* 【销售】基于条件（例如贷款利率，贷款金额等要素）快速筛选出匹配客户的金融产品\r\n* 【销售】收到新产品上架通知，进行了解和学习\r\n* 【系统】1.1版本临时功能增加和bug修复',"
						    +"'error_code': 0,"
						    +"'error_msg': 'success',"
						    +"'force_update': 0,"
						    +"'request_id': 1478604667032,"
						    +"'url': 'http://api.zhihjf.com/apk/download/financer_v1.3.0.apk',"
						    +"'version': '1.3.0',"
						    +"'version_code': 1300"+"}";
			JSONObject res = new JSONObject();
			res.put("title", "测试数据升级");
			res.put("description", "具体的信息内容");
			res.put("type", 2);
			res.put("data",data);
//			PushTransmissiontoSingleTest(push,"NN6HinJail73uhWQFcGM41","hWUINF1y6l9IMqyzIpq9iA","iT1jNA5YF47k0tZcitglm9");
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

}
